package com.dotstone.chipism.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public abstract class LazyFragment extends Fragment{
      private boolean isPrepared;
      @Override
      public void onActivityCreated(Bundle savedInstanceState) {
                 super.onActivityCreated(savedInstanceState);
                 initPrepare();
     }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return LayoutInflater.from(getContext()).inflate(getLayoutId() , null , false);
    }

    public abstract int getLayoutId();

      public void initView(){};



         /**
        * 第一次onResume中的调用onUserVisible避免操作与onFirstUserVisible操作重复
       */
             private boolean isFirstResume = true;

             @Override
      public void onResume() {
               super.onResume();
                if (isFirstResume) {
                        isFirstResume = false;
                        return;
                    }
               if (getUserVisibleHint()) {
                        onUserVisible();
                     }
            }
             @Override
            public void onPause() {
               super.onPause();
               if (getUserVisibleHint()) {
                         onUserInvisible();
                     }
             }

      private boolean isFirstVisible = true;
      private boolean isFirstInvisible = true;

              @Override
     public void setUserVisibleHint(boolean isVisibleToUser) {
         super.setUserVisibleHint(isVisibleToUser);
         if (isVisibleToUser) {
                if (isFirstVisible) {
                         isFirstVisible = false;
                         initPrepare();
                     } else {
                         onUserVisible();
                    }
            } else {
               if (isFirstInvisible) {
                         isFirstInvisible = false;
                        onFirstUserInvisible();
                    } else {
                        onUserInvisible();
                     }
             }
    }

      public synchronized void initPrepare() {
       if (isPrepared) {
                onFirstUserVisible();
             } else {
                 isPrepared = true;
             }
    }

      /**
        * 第一次fragment可见（进行初始化工作）
        */
      public void onFirstUserVisible() {

    }

      /**
        * fragment可见（切换回来或者onResume）
       */
      public void onUserVisible() {

      }

      /**
        * 第一次fragment不可见（不建议在此处理事件）
        */
      public void onFirstUserInvisible() {

     }

    /**
     * fragment不可见（切换掉或者onPause）
     */
    public void onUserInvisible() {

    }
}
